package cn.stronglink.assetmanage.business.inspection.view.wait;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.stronglink.assetmanage.MyApplication;
import cn.stronglink.assetmanage.R;
import cn.stronglink.assetmanage.business.inspection.adapter.PatrolListAdapter;
import cn.stronglink.assetmanage.business.inspection.adapter.PatrolOrderAdapter;
import cn.stronglink.assetmanage.business.inspection.model.WaitPatrolModel;
import cn.stronglink.assetmanage.business.inspection.presenter.WaitPatrolPresenter;
import cn.stronglink.assetmanage.business.inventory.view.IRefreshList;
import cn.stronglink.assetmanage.dao.DaoManager;
import cn.stronglink.assetmanage.dao.PatrolDao;
import cn.stronglink.assetmanage.dao.SyncTypesDao;
import cn.stronglink.assetmanage.entity.Patrol;
import cn.stronglink.assetmanage.entity.PatrolDetail;
import cn.stronglink.assetmanage.entity.Result;
import cn.stronglink.assetmanage.entity.SyncTypes;
import cn.stronglink.assetmanage.entity.User;
import cn.stronglink.assetmanage.index.view.onRecyclerListener;
import cn.stronglink.assetmanage.utils.Constants;
import cn.stronglink.assetmanage.utils.ToastUtil;
import cn.stronglink.netrequest.business.patrol.PatrolService;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 未巡检列表
 * Created by zhengjinglan on 2018/6/15.
 */

public class WaitPatrolFragment extends Fragment implements View.OnClickListener,IRefreshList {
    private RecyclerView rv_patrol_order_list;
    private ExpandableListView rv_patrol_list;
    private Button btn_patrol_uncount_qr;
    private Button btn_patrol_uncount_rfid;
    private Button btn_patrol_uncount_stop_rfid;
    private PatrolListAdapter listAdapter;
    private PatrolOrderAdapter orderAdapter;
    private WaitPatrolModel waitPatrolModel;
    private WaitPatrolView waitPatrolView;
    private WaitPatrolPresenter waitPatrolPresenter;
    private List<String> groupNameList;
    private LinearLayoutManager layoutManager;
    private TextView txt_title_left,txt_title_right,txt_main_title;
    private SwipeRefreshLayout refresh_list_wait;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_wait_repair_list, container, false);
        try {
            initViewAndData(view);
        }catch (Exception e){
            e.printStackTrace();
        }

        return view;
    }

    private void initViewAndData(View view) {

        txt_title_left = this.getActivity().findViewById(R.id.txt_left_title);
        txt_title_left.setVisibility(View.GONE);
        txt_title_right = this.getActivity().findViewById(R.id.txt_right_title);
        txt_title_right.setVisibility(View.GONE);
        txt_main_title = this.getActivity().findViewById(R.id.txt_main_title);
        txt_main_title.setText("巡检维修");

        rv_patrol_order_list = view.findViewById(R.id.rv_patrol_order_list);
        rv_patrol_list = view.findViewById(R.id.rv_patrol_list);
        btn_patrol_uncount_qr = view.findViewById(R.id.btn_patrol_uncount_qr);
        btn_patrol_uncount_rfid = view.findViewById(R.id.btn_patrol_uncount_rfid);
        btn_patrol_uncount_stop_rfid = view.findViewById(R.id.btn_patrol_uncount_stop_rfid);
        layoutManager = new LinearLayoutManager(this.getActivity(), LinearLayout.VERTICAL,false);
        rv_patrol_order_list.setLayoutManager(layoutManager);
        listAdapter = new PatrolListAdapter(getActivity());
        groupNameList = new ArrayList<>();
        groupNameList.add(getResources().getString(R.string.patrol_count));
        orderAdapter = new PatrolOrderAdapter(getActivity(), groupNameList);
        rv_patrol_order_list.setAdapter(listAdapter);
        rv_patrol_list.setAdapter(orderAdapter);
        listAdapter.setOnItemClickListener(new onRecyclerListener() {
            @Override
            public void onItemClicked(View v, int postion) {

                waitPatrolPresenter.showOrderByPosition(postion);
            }
        });

        rv_patrol_list.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                String groupName = groupNameList.get(groupPosition);
                waitPatrolPresenter.showDetailByPosition(groupName,childPosition);

                return false;
            }
        });
        btn_patrol_uncount_qr.setOnClickListener(this);
        btn_patrol_uncount_rfid.setOnClickListener(this);
        btn_patrol_uncount_stop_rfid.setOnClickListener(this);
        waitPatrolModel = new WaitPatrolModel();
        waitPatrolView = new WaitPatrolView(this, view, listAdapter, orderAdapter);
        waitPatrolPresenter = new WaitPatrolPresenter(waitPatrolModel, waitPatrolView);

        refresh_list_wait = view.findViewById(R.id.refresh_list_wait);
        refresh_list_wait.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                queryList();
            }
        });
        this.refreshList();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }


    @Override
    public void onClick(View v) {

    }

    @Override
    public void refreshList() {
        refreshListHandler.sendEmptyMessage(0);
    }

    private Handler refreshListHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            refreshData();
        }

        private void refreshData(){
            waitPatrolPresenter.initInventoryListView();
        }
    };


    public void queryList(){
        // 1.自动 2.离线

        SyncTypes syncType = DaoManager.getDaoSession(getContext()).getSyncTypesDao()
                .queryBuilder().where(SyncTypesDao.Properties.IsSelected.eq(true)).unique();
        int tp =0;
        if (syncType != null) {
            tp =syncType .getSyscTs();
        }

        if (tp == 1) {
            getRepairData();
        }else {
            refreshList();
            ToastUtil.toastShort("本地巡检列表加载完成");
            refresh_list_wait.setRefreshing(false);
        }
    }

    /**
     * 从服务器获取巡检单
     */
    public void getRepairData(){
        try {
            //获取之前先把已巡检的上传

            PatrolService patrolService = new PatrolService();
            patrolService.downloadPatrolWorkOrder(User.getInstance().getId_(), new Callback() {
                @Override
                public void onFailure(Call call, final IOException e) {
                    refreshListHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    refresh_list_wait.setRefreshing(false);
                                    ToastUtil.toastShort(e.getMessage());
                                }
                            });
                        }
                    });
                }

                @Override
                public void onResponse(Call call, final Response response) throws IOException {
                    try {
                        if (response.isSuccessful()) {
                            if (response.code() == 200) {
                                final String resultJson = response.body().string();

                                if (resultJson != null && !"".equals(resultJson)) {
                                    //查询是否有巡检单，如果没有就不再下载资产列表
                                    refreshListHandler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            boolean saveResult = savePatrolData(resultJson);
                                            if (saveResult){

                                                getActivity().runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        refresh_list_wait.setRefreshing(false);
                                                        ToastUtil.toastShort("巡检单下载完成");
                                                        //刷新列表
                                                        refreshList();
                                                    }
                                                });

                                            }else {
                                                getActivity().runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        refresh_list_wait.setRefreshing(false);
                                                    }
                                                });
                                            }
                                        }
                                    });


                                } else {
                                    getActivity().runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            refresh_list_wait.setRefreshing(false);
                                            ToastUtil.toastShort(MyApplication.APP_CONTEXT.getString(R.string.get_data_fail));
                                        }
                                    });

                                }
                            }else {
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        refresh_list_wait.setRefreshing(false);
                                        ToastUtil.toastShort(response.message());
                                        }
                                });

                            }
                        }else {
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    refresh_list_wait.setRefreshing(false);
                                    ToastUtil.toastShort(MyApplication.APP_CONTEXT.getString(R.string.get_data_fail));
                                }
                            });

                        }
                    }catch (Exception e){
                        e.printStackTrace();
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                refresh_list_wait.setRefreshing(false);
                            }
                        });
                    }
                }
            });
        }catch (Exception e){
            e.printStackTrace();
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    refresh_list_wait.setRefreshing(false);
                }
            });
        }
    }


    /**
     * 保存巡检单到本地
     * @param resultJson
     * @return
     */
    public boolean savePatrolData(String resultJson){
        //id为单号 patrol_id是主键
        List<Patrol> patrolList = DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getPatrolDao().queryBuilder().distinct()
                .orderAsc(PatrolDao.Properties.Id).list();

        Map<String, Patrol> patrolMap = new HashMap<>();    //巡检到的商品
        for (int i=0; i<patrolList.size();i++){
            Patrol detail = patrolList.get(i);
            patrolMap.put(patrolList.get(i).getId_(),detail);
        }
        Gson gson = new Gson();
        DaoManager.getDaoSession(MyApplication.APP_CONTEXT).clear();
        Result<List<Patrol>> repairResult = null;
        repairResult = gson.fromJson(resultJson, new  TypeToken<Result<List<Patrol>>>(){
        }.getType());
        if(repairResult!=null&&repairResult.getHttpCode()== HttpURLConnection.HTTP_OK){
            if(repairResult.getData()!=null) {
                //遍历下载的的patrol和数据库中的patrol， 如果数据库中有就将数据库中的patrol给下载的patrol列表
                List<Patrol> inventoryList = repairResult.getData();

                // 巡检单列表
                if(inventoryList!=null&&inventoryList.size()>0){
                    for(Patrol patrol:inventoryList){
                        String  id_ = patrol.getId_();
                        if (!patrolMap.containsKey(id_)){
                            DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getPatrolDao().insert(patrol);
                            // 获取详情
                            if(patrol.getDetailList()!=null&&patrol.getDetailList().size()>0){
                                for (PatrolDetail detail:patrol.getDetailList()){
                                    detail.setOrderNo(patrol.getId_());
                                    DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getPatrolDetailDao().insert(detail);
                                }
                            }
                        }


                    }
                }

            }
            return true;
        }
        return false;
    }

}
